package com.essence.grabiec104.grab.task;

import com.essence.common.task.IntervalTask;
import com.essence.common.task.TaskLauncher;
import com.essence.grabiec104.grab.service.GrabberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
@Slf4j
public class RemoveDataSchedule {
    public static final TaskLauncher LAUNCHER = new TaskLauncher(1);
    @Autowired
    private GrabberService grabberService;
    @Value("${grabber.database.retainNumber}")
    private int retainNumber;
    @Value("${grabber.database.retainDuration}")
    private int retainDuration;

    @PostConstruct
    public void doTask() {
        LAUNCHER.addTask(new IntervalTask("RemoveData", 24 * 60 * 60, 24 * 60 * 60) {
            @Override
            public void execute(String taskName, TaskLauncher launcher) throws Exception {
                log.info("开始执行数据删除任务...");
                // 根据时间节点，将历史数据删除
                int millisecondsInDay = 24 * 60 * 60 * 1000;
                long timestamp = System.currentTimeMillis() - (long) retainDuration * millisecondsInDay;
                grabberService.deleteHistoryData(timestamp);

                // 保留最近N条数据
                int count = retainNumber * 10000;
                grabberService.retainLatestData(count);
            }

            @Override
            public void notifyFailure(String taskName, int consecutiveFailures, TaskLauncher launcher, Exception ex) {
                log.error("{} notifyFailure", taskName, ex);
            }

            @Override
            public void notifySuccess() {
                log.info("数据删除任务执行成功");
            }
        });
    }
}
